﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MvcPipe.Samples.Web.Controllers
{
    public class HomeController : PipeletController
    {
        public void IndexAsync()
        {
            var pipelets = new Dictionary<string, PipeletDescription>()
            {
                {"BannerContent01",     new PipeletDescription() { Action = "BannerContent"}},
                {"MainContent",         new PipeletDescription()},
                {"AlternativeContent",  new PipeletDescription()},
                {"BannerContent02",     new PipeletDescription() { Action = "BannerContent"}}
            };        

            ExecutePipelets(pipelets);
        }

        public ActionResult IndexCompleted()
        {
            return new EmptyResult();
        }

        public ActionResult BannerContent()
        {
            return PartialView(DateTime.UtcNow);
        }

        public void MainContentAsync()
        {
            WaitFor(5000);     
        }

        public ActionResult MainContentCompleted()
        {
            return PartialView(DateTime.UtcNow);
        }

        public void AlternativeContentAsync()
        {
            WaitFor(10000);
        }

        public ActionResult AlternativeContentCompleted()
        {
            return PartialView(DateTime.UtcNow);
        }

        private void WaitFor( int milliseconds )
        {
            Timer timer = null;

            AsyncManager.OutstandingOperations.Increment(); 

            timer = new Timer(state =>
            {
                AsyncManager.OutstandingOperations.Decrement();
                timer.Dispose();                  
            },null,milliseconds,-1);
        }
    }
}
